package com.ocom.webapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.MapKey;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.dto.*;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityResourceMenu;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.companyrole.GetCompanyConfigRequest;
import com.ocom.common.request.company.companyrole.GetPageByRoleRequest;
import com.ocom.common.request.company.companyrole.SetPageByRoleRequest;
import com.ocom.common.request.company.companyrole.UpdateCompanyRoleRequest;
import com.ocom.common.request.web.ConsumeUnitsShowRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.PasswordValidator;
import com.ocom.common.utils.ResultUtil;
//import com.ocom.common.utils.pwd.HandlePasswordUtil;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.common.vo.company.CompanyRoleListVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.service.CompanyService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


//@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@Log4j
@RestController
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    CompanyClientService companyClientService;

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    HumanClientService humanClientService;

    /**
     * 单位列表（UnitsPage/onShow）
     */
    @GetMapping(CompanyServiceUrl.URL_UnitsPageOnShow)
    public Result UnitsPageOnShow(Long comId, String comName, Integer agentId, Integer page, Integer size) {
//        if(agentId==null){
//            agentId = SecurityUtils.getYoCiUser().getComId().intValue();
//        }
        return companyService.UnitsPageOnShow(comId, comName, agentId, page, size);
    }


    /**
     * 单位信息
     */
    @GetMapping(CompanyServiceUrl.URL_UnitsPageInfo)
    public Result UnitsPageInfo(Long comId) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        EntityCompanyInfo entityCompanyInfo = companyService.UnitsPageInfo(comId);
        entityCompanyInfo.setRole(yoCiUser.getRole());
        if (yoCiUser.getRole() == 41l || yoCiUser.getRole() == 42l || yoCiUser.getMerchId()>0l) {
            Long merchId = yoCiUser.getMerchId();
            entityCompanyInfo.setMerchId(merchId);
            Result result = payConfigClientService.GetMerchInfo(comId, merchId.intValue());
            if (result.getCode() == 200) {
                EntityXfMerchantInfo entityXfMerchantInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfMerchantInfo.class);
                entityCompanyInfo.setMerchName(entityXfMerchantInfo.getMerchName());
            }
        }

        return ResultUtil.success(entityCompanyInfo);
    }


    /**
     * 修改密码   UserPage/modify
     */
    @PostMapping(CompanyServiceUrl.URL_UserPageModify)
    public Result UserPageModify(@Validated @RequestBody UnitsPageModifyDto unitsPageModifyDto) {
//        if(!HandlePasswordUtil.isWeekPassword(unitsPageModifyDto.getPassword())){
//            return ResultUtil.error(ResultEnum.Err_3107);
//        }

        List<String> errors = PasswordValidator.validatePassword(unitsPageModifyDto.getPassword());

        if (!errors.isEmpty()) {
            return ResultUtil.info(500,String.join(",",errors));
        }

        Map<String, Object> map = new HashMap<>();
        MapKey key = new MapKey();
        map.put(key.getKey_userName(), SecurityUtils.getUsername());
        map.put(key.getKey_password(), unitsPageModifyDto.getPassword());
        companyService.UserPageModify(map);
        return ResultUtil.success();
    }

    /**
     * 单位信息修改
     */
    @PostMapping(CompanyServiceUrl.URL_UnitsPageModify)
    public Result UnitsPageModify(@Validated @RequestBody CompanyInfoDto companyInfoDto) {
        return companyService.UnitsPageModify(companyInfoDto);
    }


    /**
     * 单位信息新增
     */
    @PostMapping(CompanyServiceUrl.URL_UnitsPageAdd)
    public Result UnitsPageAdd(@Validated @RequestBody UnitsPageModifyDto unitsPageModifyDto) {
        JSONObject  jsonObject= getHeadersInfo();
        if(jsonObject.getString("remoteip")!=null && !jsonObject.getString("remoteip").equals("183.6.79.233")){
            return ResultUtil.error(ResultEnum.Err_4,jsonObject);
        }
        unitsPageModifyDto.setIsAgent(0l);
        unitsPageModifyDto.setAgentId(SecurityUtils.getYoCiUser().getComId());

        List<String> errors = PasswordValidator.validatePassword(unitsPageModifyDto.getPassword());
        if (!errors.isEmpty()) {
            return ResultUtil.info(500,String.join(",",errors));
        }

        return companyService.UnitsPageAdd(unitsPageModifyDto);
    }

    @Autowired
    private HttpServletRequest httpServletRequest;

    //get request headers
    private JSONObject getHeadersInfo() {
        JSONObject jsonObject = new JSONObject();
        Enumeration headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = httpServletRequest.getHeader(key);
            jsonObject.put(key, value);
        }
        return jsonObject;
    }

    /*
     * @Description:通讯密钥生成
     * @Author: lu
     * @Date: 2022/4/26 15:07
     * @param unitsPageModifyDto:
     * @return: com.ocom.common.resp.Result
     **/
    @GetMapping(CompanyServiceUrl.URL_UnitsPageBuildKey)
    public Result unitsPageBuildKey(Long comId) {
        return companyService.unitsPageBuildKey(comId);
    }


    @GetMapping(CompanyServiceUrl.URL_getCompanyListByAgentId)
    public Result getCompanyIdsByAgentId() {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        return companyClientService.getCompanyListByAgentId(yoCiUser.getComId());
    }


    // 2.8.1消费单位列表（ConsumeUnits/onShow）
    @PostMapping(WebApiServiceUrl.Url_ConsumeUnitsOnShow)
    public Result ConsumeUnitsShow(@RequestBody ConsumeUnitsShowRequest request) {
        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        companyListInfoVo.setComId(request.getComId());
        companyListInfoVo.setComName(request.getComName());
        companyListInfoVo.setAgentId(request.getAgentId());
        if (request.getAgentId() == null && SecurityUtils.getYoCiUser().getComId() != 1l) {
            companyListInfoVo.setAgentId(SecurityUtils.getYoCiUser().getComId());
        }
        companyListInfoVo.setPage(request.getPage());
        companyListInfoVo.setSize(request.getSize());
        return companyClientService.GetCompanyListInfo(companyListInfoVo);
    }


    @PostMapping(WebApiServiceUrl.Url_UnitsPageGetCompanyRole)
    public Result unitsPageGetCompanyRole(@Validated @RequestBody GetCompanyRoleListDto request) {
        return companyClientService.getCompanyRole(request);
    }

    @PostMapping(WebApiServiceUrl.Url_UnitsPageAddCompanyRole)
    public Result addCompanyRole(@Validated @RequestBody CompanyRoleDto request) {
        return companyClientService.addCompanyRole(request.getComId(), request);
    }

    @PostMapping(WebApiServiceUrl.Url_UnitsPageModifyCompanyRole)
    public Result modifyCompanyRole(@Validated @RequestBody UpdateCompanyRoleRequest request) {
        return companyClientService.modifyCompanyRole(request.getComId(), request.getRoleId(), request.getRoleName());
    }

    @PostMapping(WebApiServiceUrl.Url_UnitsPageDelCompanyRole)
    public Result delCompanyRole(@Validated @RequestBody UpdateCompanyRoleRequest request) {
        if (null == request.getRoleId() || 10000l > request.getRoleId()) {
            return ResultUtil.error(ResultEnum.Err_3016);
        }
        humanClientService.deleteRolePermission(request.getRoleId().intValue());
        return companyClientService.delCompanyRole(request.getComId(), request.getRoleId());
    }

    @PostMapping(WebApiServiceUrl.Url_UnitsPageGetPageByRole)
    public Result getPageByRole(@Validated @RequestBody GetPageByRoleRequest request) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();

        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        companyListInfoVo.setComId(yoCiUser.getComId());
        companyListInfoVo.setPage(1);
        companyListInfoVo.setSize(1);
        Result companyListResult = companyClientService.GetCompanyListInfo(companyListInfoVo);
        List<GetCustomRolePowerDto> getCustomRolePowerDtoList = new ArrayList<>();
        List<EntityResourceMenu> parentMenus = new ArrayList<>();
        if (companyListResult.getCode() == 200) {
            try {
                Map map = JSON.parseObject(JSON.toJSONString(companyListResult.getData()), Map.class);
                List<UnitsPageOnShowDto> companyListDtoList = JSON.parseArray(JSON.toJSONString(map.get("list")), UnitsPageOnShowDto.class);
                UnitsPageOnShowDto companyListDto = companyListDtoList.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("saasNo", companyListDto.getSaasId());
                jsonObject.put("xfVer", companyListDto.getXfStatus());
                jsonObject.put("mjVer", companyListDto.getMjStatus());
                jsonObject.put("ifCustom",1);
                GetCompanyRoleListDto getCompanyRoleListDto = new GetCompanyRoleListDto();
                getCompanyRoleListDto.setComId(yoCiUser.getComId());
                getCompanyRoleListDto.setRoleId(request.getRoleId());
                Result companyRoleResult = companyClientService.getCompanyRole(getCompanyRoleListDto);
                if (200 == companyRoleResult.getCode()) {
                    List<CompanyRoleListVo> companyRoleListVos = JSON.parseArray(JSON.toJSONString(companyRoleResult.getData()), CompanyRoleListVo.class);
                    if (null != companyRoleListVos && 0 < companyRoleListVos.size()) {

                        jsonObject.put("role", companyRoleListVos.get(0).getParentRole());
                        Result parentTreeResult = humanClientService.getSaasMenuByRole(jsonObject);
                        if (200 == parentTreeResult.getCode()) {
                            Map parentMenuMap = JSON.parseObject(JSON.toJSONString(parentTreeResult.getData()), Map.class);
                            parentMenus = JSON.parseArray(JSON.toJSONString(parentMenuMap.get("menuTree")), EntityResourceMenu.class);

                            if (parentMenus != null && 10000 < request.getRoleId()) {
                                JSONObject getCustomRolePowerJson = new JSONObject();
                                getCustomRolePowerJson.put("role", request.getRoleId());
                                getCustomRolePowerJson.put("comId", yoCiUser.getComId());
                                Result getCustomRolePowerResult = humanClientService.getCustomRolePower(getCustomRolePowerJson);
                                if (200 == getCustomRolePowerResult.getCode()) {
                                    getCustomRolePowerDtoList = JSON.parseArray(JSON.toJSONString(getCustomRolePowerResult.getData()), GetCustomRolePowerDto.class);
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> returnResult = new HashMap<>();
        returnResult.put("menuTree", parentMenus);
        returnResult.put("roleList", getCustomRolePowerDtoList);
        return ResultUtil.success(returnResult);
    }

    @PostMapping(WebApiServiceUrl.Url_UnitsPageSetPageByRole)
    public Result setPageByRole(@Validated @RequestBody SetPageByRoleRequest request) {
        return humanClientService.setRolePermission(request);
    }


    @PostMapping(WebApiServiceUrl.URL_CompanyConfigOnShow)
    public Result companyConfigOnShow(@Validated @RequestBody GetCompanyConfigRequest request) {
        return companyClientService.getCompanyConfig(request.getComId(), request.getTab());
    }

    @PostMapping(WebApiServiceUrl.URL_CompanyConfigDelete)
    public Result companyConfigDelete(@Validated @RequestBody GetCompanyConfigRequest request) {
        return companyClientService.removeCompanyConfig(request.getComId(), request.getTab());
    }

    @PostMapping(WebApiServiceUrl.URL_CompanyConfigAdd)
    public Result companyConfigAdd(@Validated @RequestBody EntityCompanyConfig request) {
        return companyClientService.addCompanyConfig(request);
    }
    @PostMapping(WebApiServiceUrl.URL_CompanyConfigModify)
    public Result companyConfigModify(@Validated @RequestBody EntityCompanyConfig request) {
        return companyClientService.updateCompanyConfig(request);
    }


    @PostMapping(WebApiServiceUrl.URL_mjAreaState)
    public Result studentOnlineShow(){
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        try {
            Result<List<EntityCompanyConfig>> mjSMS = companyClientService.getCompanyConfig(yoCiUser.getComId(), "regionOnline");
            if (mjSMS.getCode() == 200) {

                String s1 = mjSMS.getData().get(0).getConfig().replaceAll("\\\\", "");
                return ResultUtil.success(JSON.parseArray(s1));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String,Object> objectMap=new HashMap<>();
        objectMap.put("state",0);
        objectMap.put("name","未知");
        List<Object> ij = new ArrayList<>();
        ij.add(objectMap);
        return ResultUtil.success(ij);
    }

}
